from typing import Optional

from fastapi import APIRouter,Depends
from pydantic import BaseModel

from backend.app.app.crud_pro.tb_userpro_share import get_all_share_db, new_share, get_share_proj, \
    get_create_proj_user_id
from backend.app.app.api.api_v1.user import verify_token_user

router_share_project = APIRouter(prefix="/share_project", tags=["共享工程"])

class u_id(BaseModel):
    user_id : str
    user_name : str

#获取到自己共享出去的工程
@router_share_project.post("/get_all_share",name="获取用户共享给别人的工程")
async def get_all_share(u_id:u_id,ver = Depends(verify_token_user)):
    all = get_all_share_db(u_id.user_id,u_id.user_name)
    return {"all_share_information":all,"ver_token":ver}

class share_pro_inf(BaseModel):
    project_id:str
    project_name:str
    user_id:str
    user_name: str
    share_user:str = '{"ProjShared_UserID": 1,"ProjShared_UserName": "test1"},{"ProjShared_UserID": 3,"ProjShared_UserName": "test3"}'
    ProjShared_PermitType: str = "可另存"
    remark:Optional[str]=None

@router_share_project.post("/new_share_project", name="新建共享工程")
async def new_share_project(share_inf: share_pro_inf,ver=Depends(verify_token_user)):
    if share_inf.project_id is None or share_inf.project_name is None:
        return {
            'result': False,
            'error': 'Proj unexisted',
            "ver_token": ver,
        }
    elif share_inf.user_id is None or share_inf.user_name is None:
        return {
            'result': False,
            'error': 'User unexisted',
            "ver_token": ver,
        }
    if share_inf.ProjShared_PermitType not in ['只读', '可另存', '无']:
        return {
            'result': False,
            'error': 'ProjShared_PermitType type error',
            'ver_token': ver,
        }

    result = new_share(
        project_id=share_inf.project_id,
        project_name=share_inf.project_name,
        user_id=share_inf.user_id,
        user_name=share_inf.user_name,
        share_user=share_inf.share_user,
        ProjShared_PermitType=share_inf.ProjShared_PermitType,
        remark=share_inf.remark
    )
    return {
        "result":result,
        "ver_token": ver
    }

class get_share_project_request(BaseModel):
    proj_id: str
    user_id: str

@router_share_project.post("/get_share_project", name="获得共享工程")
async def get_share_project(share_project:get_share_project_request,ver=Depends(verify_token_user)):
    result = get_share_proj(share_project.proj_id,share_project.user_id)
    return {
        "result": result,
        "ver_token": ver
    }

class proj_id_model(BaseModel):
    proj_id:str

@router_share_project.post("/get_create_user_id", name="获得共享工程用户的ID")
async def get_create_user_id(proj_id:proj_id_model,ver=Depends(verify_token_user)):
    result = get_create_proj_user_id(proj_id.proj_id)
    return {
        "result": result,
        "ver_token": ver
    }